package one.bugu.android.demon.ui.activity.snatch;

import android.annotation.SuppressLint;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.juefeng.android.framework.LKUtil;
import com.juefeng.android.framework.view.annotation.LKContentView;
import com.juefeng.android.framework.view.annotation.LKInjectView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import one.bugu.android.demon.R;
import one.bugu.android.demon.common.BaseHttpAsycResponceHandler;
import one.bugu.android.demon.common.MyBaseActivity;
import one.bugu.android.demon.constant.Constant;
import one.bugu.android.demon.constant.HttpConstant;
import one.bugu.android.demon.ui.activity.WebActivity;
import one.bugu.android.demon.ui.adapter.snatch.FragmentAdapter;
import one.bugu.android.demon.ui.fragment.snatch.BuyingEndFragment;
import one.bugu.android.demon.ui.fragment.snatch.BuyingFragment;
import one.bugu.android.demon.ui.widget.BaseTopBarView;
import one.bugu.android.demon.ui.widget.MarqueeTextView;
import one.bugu.android.demon.util.IntentUtils;
import one.bugu.android.demon.util.ParamUtils;
import one.bugu.android.demon.util.PreferencesUtil;
import one.bugu.android.demon.util.StatusBarUtils;
import one.bugu.android.demon.util.TimerTaskUtils;

/**
 * Description SnatchActivity 夺宝
 *
 * @author liuxin
 * @date 2018/10/26 9:53
 */
@LKContentView(R.layout.activity_snatch_layout)
public class SnatchActivity extends MyBaseActivity implements View.OnClickListener {

    @LKInjectView(R.id.btbv_snatch)
    private BaseTopBarView btbvSnatch;

    @LKInjectView(R.id.iv_snatch_banner)
    private ImageView snatchBanner;

    @LKInjectView(R.id.rl_buying)
    private RelativeLayout rlBuying;

    @LKInjectView(R.id.iv_tab_image)
    private ImageView ivTabImage;

    @LKInjectView(R.id.tv_buying)
    private TextView tvBuying;

    @LKInjectView(R.id.view_buying)
    private View viewBuying;

    @LKInjectView(R.id.rl_buying_end)
    private RelativeLayout rlBuyingEnd;

    @LKInjectView(R.id.tv_end_buying)
    private TextView tvEndBuying;

    @LKInjectView(R.id.view_buying_end)
    private View viewBuyingEnd;

    @LKInjectView(R.id.vp_snatch)
    private ViewPager vpSnatch;

    @LKInjectView(R.id.tv_msg_marquee)
    private MarqueeTextView tv_msg_marquee;

    @LKInjectView(R.id.ll_win_layout)
    private LinearLayout ll_win_layout;

    private static final int BUYING = 0;
    private static final int BUYING_END = 1;

    private String token;
    /**
     * 存放中奖公告
     */
    private StringBuffer buffer;

    /**
     * 中奖公告每一条信息之间间距
     */
    private final String SPACE = "                             ";
    /**
     * 刷新时间 秒
     */
    private final long TIME_INTERVAL = 60;

    @Override
    protected void initView() {
        super.initView();
        //设置状态栏
        StatusBarUtils.getInstance().setStatusBar("#FFFFFF", this, btbvSnatch, false);
        //默认显示抢购中列表
        setTab(BUYING);
        //添加页面展示fragment
        List<Fragment> fragmentList = new ArrayList<>();
        fragmentList.add(new BuyingFragment());
        fragmentList.add(new BuyingEndFragment());
        //viewpager适配器初始化
        FragmentAdapter mAdater = new FragmentAdapter(getSupportFragmentManager(), fragmentList);
        vpSnatch.setAdapter(mAdater);
    }

    @Override
    protected void initData() {
        super.initData();
        token = PreferencesUtil.getInstance().getString(this, Constant.TOKEN);
        if (buffer == null) {
            buffer = new StringBuffer();
        }
        //获取中奖公告
        getWinningAccountmentText();
    }

    @Override
    protected void initEvent() {
        super.initEvent();

        rlBuying.setOnClickListener(this);
        rlBuyingEnd.setOnClickListener(this);
        snatchBanner.setOnClickListener(this);

        btbvSnatch.setEventInterface(new BaseTopBarView.EventInterface() {
            @Override
            public void leftOnClick() {
                finish();
            }

            @Override
            public void leftCloseClick() {

            }

            @Override
            public void rightOnClick() {
                IntentUtils.startAty(SnatchActivity.this, SnatchRecordActivity.class);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_buying:
                //抢购中
                setTab(BUYING);
                break;
            case R.id.rl_buying_end:
                //抢购结束
                setTab(BUYING_END);
                break;
            case R.id.iv_snatch_banner:
                //banner图点击事件
                String inviteCode = PreferencesUtil.getInstance().getString(SnatchActivity.this, Constant.INVITE_CODE);
                List<ParamUtils.NameValue> parList = ParamUtils.build()
                        .put(WebActivity.TITLE, "邀请好友")
                        .put(WebActivity.URL, HttpConstant.SNATCH_INVITE_H5_URL + "?appType=android&code=" + inviteCode)
                        .create();
                IntentUtils.startAty(SnatchActivity.this, WebActivity.class, parList);
                break;
            default:
                break;
        }
    }

    /**
     * 获取中奖公告
     */
    private void getWinningAccountmentText() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        LKUtil.getHttpManager().postBody(HttpConstant.WINNING_ACCOUNTMENT, map, getSnatchPeriodHander);
    }

    @SuppressLint("HandlerLeak")
    private BaseHttpAsycResponceHandler getSnatchPeriodHander =
            new BaseHttpAsycResponceHandler<List<String>>() {
                @Override
                public void onSuccess(List<String> winInfo) {
                    super.onSuccess(winInfo);
                    if (winInfo != null && winInfo.size() > 0) {
                        String winningText = getWinningText(winInfo);
                        tv_msg_marquee.stopScroll();
                        ll_win_layout.setVisibility(TextUtils.isEmpty(winningText) ? View.GONE : View.VISIBLE);
                        tv_msg_marquee.setText(winningText);
                        tv_msg_marquee.setRndDuration(3000 * winInfo.size());
                        tv_msg_marquee.startScroll();
                    } else {
                        ll_win_layout.setVisibility(View.GONE);
                    }
                }

                @Override
                public void onFailed(int code, String message) {
                    super.onFailed(code, message);

                }

                @Override
                public void onError() {
                    super.onError();

                }
            };

    /**
     * 创建定时任务去请求中奖公告
     */
    private void startTimeTask() {
        TimerTaskUtils.getInstance().startRepeatTimerTask(TIME_INTERVAL, new TimerTaskUtils.OnTimerTaskEvent() {
            @Override
            public void onTickEvent(long millisUntilFinished) {

            }

            @Override
            public void onFinishEvent() {
                getWinningAccountmentText();
            }
        });
    }

    /**
     * 中奖公告数据转换
     *
     * @param listData 数据源
     * @return
     */
    private String getWinningText(List<String> listData) {
        if (buffer == null) {
            buffer = new StringBuffer();
        }
        //清除数据
        buffer.delete(0, buffer.length());
        if (listData != null) {
            for (int i = 0; i < listData.size(); i++) {
                if (i == 0) {
                    buffer.append(SPACE);
                }
                buffer.append(listData.get(i));
                buffer.append(SPACE);
            }
        }
        return buffer.toString();
    }

    /**
     * 设置tab按钮状态
     *
     * @param snatchState
     */
    private void setTab(int snatchState) {
        boolean status = snatchState == BUYING;
        vpSnatch.setCurrentItem(snatchState);
        //抢购状态
        ivTabImage.setSelected(status);
        tvBuying.setSelected(status);
        tvBuying.setTextSize(status ? 14 : 13);
        viewBuying.setVisibility(status ? View.VISIBLE : View.GONE);

        //结束状态
        tvEndBuying.setSelected(!status);
        tvEndBuying.setTextSize(!status ? 14 : 13);
        viewBuyingEnd.setVisibility(!status ? View.VISIBLE : View.GONE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //开始倒计时
        startTimeTask();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //页面不可见时停止倒计时
        TimerTaskUtils.getInstance().endTimerTask();
    }

}
